import { tablePopperConfig } from '../config'
import { createPopper } from '@popperjs/core'

export default {
  data() {
    return {
      tooltipPosition: {
        getBoundingClientRect: this.generateTooltipPosition()
      },
      tooltipInstance: null
    }
  },
  methods: {
    generateTooltipPosition(x = 0, y = 0) {
      return () => ({
        width: 0,
        height: 0,
        top: y,
        left: x
      })
    },
    updateToolTipDom(event) {
      const { tooltipEl } = this.$refs
      const { clientX, clientY, target, offsetX, offsetY } = event
      const { clientWidth, clientHeight, src } = target
      const positionY = clientY - (offsetY - clientHeight / 2)
      const positionX = clientX - (offsetX - clientWidth / 2)

      this.tooltipPosition.getBoundingClientRect = this.generateTooltipPosition(
        positionX,
        positionY
      )

      if (this.tooltipInstance) {
        tooltipEl.firstChild.src = src
        this.$nextTick(() => {
          this.tooltipInstance.update()
        })
      } else {
        const imgDom = document.createElement('img')
        imgDom.src = src
        tooltipEl.insertBefore(imgDom, tooltipEl.firstChild)
        document.body.appendChild(tooltipEl)
        this.$nextTick(() => {
          this.tooltipInstance = createPopper(
            this.tooltipPosition,
            tooltipEl,
            tablePopperConfig
          )
        })
      }
    },
    updateViewer(image) {
      this.$refs.sxViewerNode.update(image)
    }
  }
}
